(function(global){
	var Section = Yo.Section;
	var User = Yo.User;
	var Utils = Yo.Utils;

	var YoPages = {
		initPages: []
	};

	YoPages.initPages.push(function(){
		FastClick.attach(document.body);
		
		// modals
		$(document).on('click', 'a', function(e){
			var link = $(e.target);
			if(!link.is('a'))
				link = link.closest('a');

			var pageDyn = link.attr('yo-href');
			var pageStatic = link.attr('href');

			if(pageDyn){
				if(pageDyn.indexOf('#') == 0)
					pageDyn = pageDyn.substr(1);

				var paramsStr = link.attr('data-params');
				var params = Utils.str2params(paramsStr);

				Section.go(pageDyn, false, params);
			}else if(pageStatic){
				if(pageStatic.indexOf('#') == 0){
					// modal toggle, do not use touchend
					var modal = $(pageStatic);

					var isActive = modal.hasClass('active');
					modal.toggleClass('active');

					if(isActive){
						// close modal
						Section.his.remove(pageStatic);
					}else{
						Section.his.push(pageStatic);
					}
				}else{
					document.location.href = pageStatic;
				}
			}

			return false;
		});

		// history
		var isExist = 0;
		window.onpopstate = function(){
			var json = history.state;
			Yo.log.i(json);

			if(!json || !json.page){
				Section.his.backTo('');

				if(isExist > 1){
					if(navigator.app.exitApp)
						navigator.app.exitApp();
					else
						window.close();
				}else{
					isExist++;

					if(isExist > 1){
						var flag = Utils.confirm('确定要退出么？');
						if(flag)
							window.close();
					}
				}
			}else{
				Section.his.backTo(json.page);
				isExist = 0;
			}
		};

		// show default page
		var params = Utils.params();
		if(params.defaultPage){
			Section.go(params.defaultPage);
		}
	});

	YoPages.init = function(){
		var i = 0;
		for(; i < YoPages.initPages.length; i++){
			YoPages.initPages[i].call(YoPages);
		}
	};

	global.YoPages = YoPages;
})(this);